package com.woniuxy.thred.others;

/**
 * description: CAS <br>
 * date: 2022/2/6 11:07 下午 <br>
 * author: shesaifei <br>
 * version: 1.0 <br>
 */

import java.util.concurrent.atomic.AtomicInteger;

/**
 * CAS:比较并交换
 */
public class CAS {
    //库存
    private static AtomicInteger stock = new AtomicInteger(5);

    public static void main(String[] args) {
        for (int i = 0; i < 5; i++) {
            //模拟网络延时
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            new Thread(() -> {
                Integer left = stock.decrementAndGet();
                if (left < 1) {
                    System.out.println("抢完了....");
                    return;
                }
                System.out.print(Thread.currentThread().getName() + "抢了一件商品");
                System.out.println("-->还剩" + left);
            }).start();
        }
    }
}
